package com.qdsgjsfk.vision.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.base.BaseFragment;
import com.qdsgjsfk.vision.ui.dialog.ReviewDialog;
import com.qdsgjsfk.vision.ui.dialog.YearDialog;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.AxisResponse;
import com.rest.response.BaseResponse;
import com.rest.response.IsTaskDataResponse;
import com.rest.response.TaskListResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

/**
 * Created by HP on 2018/10/6.
 */

public class TaskListFragment extends BaseFragment {

    @BindView(R.id.recyclerView_student_list)
    RecyclerView recyclerView_student_list;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_task)
    TextView tv_task;

    List<TaskListResponse.Task> list = new ArrayList<>();
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.iv_bottom_collect)
    ImageView ivBottomCollect;
    @BindView(R.id.rl_collect)
    RelativeLayout rlCollect;
    @BindView(R.id.tv_history)
    TextView tvHistory;
    @BindView(R.id.iv_bottom_history)
    ImageView ivBottomHistory;
    @BindView(R.id.rl_history)
    RelativeLayout rlHistory;
    @BindView(R.id.ll_year)
    LinearLayout llYear;
    Unbinder unbinder;
    @BindView(R.id.tv_year)
    TextView tvYear;

    private long classId;
    private int planType, status = 0;
    private String schoolName, mPlanYear;
    Bundle bundle;
    MyAdapter myAdapter;
    //    private ClassDialog mClassDialog;
    private ReviewDialog mReviewDialog;
    private YearDialog mYearDialog;
    private int currentPage = 1;


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_task_list;
    }

    @Override
    protected void initView() {
        myAdapter = new MyAdapter();
        recyclerView_student_list.setLayoutManager( new LinearLayoutManager( mContext ) );
        recyclerView_student_list.setAdapter( myAdapter );
        refreshLayout.setRefreshFooter( new BallPulseFooter( mContext ).setSpinnerStyle( SpinnerStyle.Scale ) );
        refreshLayout.setRefreshHeader( new ClassicsHeader( mContext ) );
        refreshLayout.setEnableLoadMore( true );
        refreshLayout.setOnRefreshListener( refreshlayout -> getTaskList(false) );
        refreshLayout.setOnLoadMoreListener( refreshlayout -> {
            getTaskList(true);
        } );

    }

    @Override
    protected void initData() {
        assert getArguments() != null;
        classId = getArguments().getLong( "classId" );
        planType = getArguments().getInt( "planType", -1 );
        schoolName = getArguments().getString( "schoolName" );
        refreshLayout.autoRefresh();
    }

    public static TaskListFragment newInstance(int planType) {
        Bundle args = new Bundle();
        args.putInt( "planType", planType );
        TaskListFragment fragment = new TaskListFragment();
        fragment.setArguments( args );
        return fragment;
    }


    @OnClick({R.id.rl_collect, R.id.rl_history, R.id.ll_year})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_collect:
                //筛查状态 status  ：  0 待筛查  1 已筛查 2-全部
                status = 0;
                tvCollect.setTextColor( ContextCompat.getColor( mContext, R.color.mainColor ) );
                tvHistory.setTextColor( ContextCompat.getColor( mContext, R.color.commonGrey ) );
                ivBottomCollect.setVisibility( View.VISIBLE );
                ivBottomHistory.setVisibility( View.GONE );
                getTaskList(false);
                break;
            case R.id.rl_history:
                status = 1;
                tvHistory.setTextColor( ContextCompat.getColor( mContext, R.color.mainColor ) );
                tvCollect.setTextColor( ContextCompat.getColor( mContext, R.color.commonGrey ) );
                ivBottomHistory.setVisibility( View.VISIBLE );
                ivBottomCollect.setVisibility( View.GONE );
                getTaskList(false);
                break;
            case R.id.ll_year:
                //planYear
                showYearDialog();
                break;
        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.TaskHolder> {
        int checkPosition = -1;

        @NonNull
        @Override
        public TaskHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new TaskHolder( getLayoutInflater().inflate( R.layout.item_task, parent, false ) );
        }

        @Override
        public void onBindViewHolder(TaskHolder holder, @SuppressLint("RecyclerView") final int position) {
            holder.tv_project.setText( list.get( position ).checkOption );
            holder.tv_date.setText( list.get( position ).taskTime );
            holder.tv_school.setText( list.get( position ).taskOrgName );
            holder.tv_worker.setText( list.get( position ).workers );
            holder.tv_twice.setText( list.get( position ).planName );
            String status = list.get( position ).status;
            String planType = list.get( position ).planType;
            //筛查状态 status  ：  0 待筛查  1 已筛查 2-全部
            if ("0".equals( status )) {
                holder.tv_status.setTextColor( ContextCompat.getColor( mContext, R.color.FF932D ) );
                holder.tv_status.setText( "进行中" );
            } else if ("1".equals( status )) {
                holder.tv_status.setTextColor( ContextCompat.getColor( mContext, R.color.commonGrey ) );
                holder.tv_status.setText( "已完成" );
            }
            //计划类型： 101-普查计划 102-抽查计划 103-复查计划
            if ("101".equals( planType )) {
                holder.tv_plan_type.setText( "普查" );
            } else if ("102".equals( planType )) {
                holder.tv_plan_type.setText( "抽查" );
            } else if ("103".equals( planType )) {
                holder.tv_plan_type.setText( "复查" );
            } else if ("104".equals( planType )) {
                holder.tv_plan_type.setText( "自查" );
            }
//                ((StudentHolder) holder).progressSelf.setProgress(listWithLetter.get(position).schedule);
//                ((StudentHolder) holder).examinationDate.setText(listWithLetter.get(position).examinationDate);
            holder.itemView.setOnClickListener( v -> {
                if (TaskListFragment.this.planType == 1) {
                    Toast.makeText( mContext, "任务已结束，无法查看", Toast.LENGTH_SHORT ).show();
                    return;
                }
                bundle = new Bundle();
                bundle.putString( "taskSchoolId", list.get( position ).taskOrgId );
                bundle.putString( "taskId", list.get( position ).taskId );
                bundle.putString( "schoolName", list.get( position ).taskOrgName );
                isTask( list.get( position ).taskId );
//                    showSchoolDialog(list.get(position).taskSchoolId,list.get(position).taskId,list.get(position).schoolName);
            } );
            holder.ll_open_close.setOnClickListener( v -> {
                if (checkPosition == position) {
                    if (holder.ll_project.getVisibility() == View.VISIBLE) {
                        holder.ll_project.setVisibility( View.GONE );
                        holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_open ) );
                    } else {
                        holder.ll_project.setVisibility( View.VISIBLE );
                        holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_close_task ) );
                    }

                } else {
                    if (holder.ll_project.getVisibility() == View.VISIBLE) {
                        holder.ll_project.setVisibility( View.GONE );
                        holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_open ) );
                    } else {
                        holder.ll_project.setVisibility( View.VISIBLE );
                        holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( mContext, R.mipmap.icon_close_task ) );
                    }
                }
                checkPosition = position;
            } );
//            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    if (type == 1) {
//                        showReviewDialog(list.get(position).taskId, type);
//                    } else {
//                        showReviewDialog(list.get(position).taskId, type);
//                    }
//                    return false;
//                }
//            });
        }


        @Override
        public int getItemCount() {
            return list.size();
        }


        class TaskHolder extends RecyclerView.ViewHolder {
            TextView tv_project, tv_school, tv_worker, tv_date, tv_twice, tv_status, tv_plan_type;
            LinearLayout ll_open_close, ll_project;
            ImageView iv_open_close;

            TaskHolder(View itemView) {
                super( itemView );
                tv_project = itemView.findViewById( R.id.tv_project );
                tv_school = itemView.findViewById( R.id.tv_school );
                tv_worker = itemView.findViewById( R.id.tv_worker );
                tv_date = itemView.findViewById( R.id.tv_date );
                tv_twice = itemView.findViewById( R.id.tv_twice );
                tv_status = itemView.findViewById( R.id.tv_status );
                tv_plan_type = itemView.findViewById( R.id.tv_plan_type );
                ll_open_close = itemView.findViewById( R.id.ll_open_close );
                ll_project = itemView.findViewById( R.id.ll_project );
                iv_open_close = itemView.findViewById( R.id.iv_open_close );
            }
        }


    }

    private void getTaskList(Boolean loadMore) {

        if (loadMore){
            currentPage ++;
        }else {
            currentPage = 1;
        }
        RestProxy.getInstance().getTaskList(currentPage,status + "", "", "", "", mPlanYear, planType + "", new Observer<TaskListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TaskListResponse taskListResponse) {
                if (loadMore){
                    refreshLayout.finishLoadMore();
                }else {
                    refreshLayout.finishRefresh();
                }
                try {
                    if (taskListResponse.data != null && taskListResponse.data.list != null) {
                        if (loadMore){
                            if (taskListResponse.data.list.size() > 0) {
                                tv_task.setVisibility( View.GONE );
                                recyclerView_student_list.setVisibility( View.VISIBLE );
                                list.addAll( taskListResponse.data.list );
                                myAdapter.notifyDataSetChanged();
                            }else {
                                ToastUtil.showToast(getContext(),"没有更多数据");
                            }
                        }else {
                            if (taskListResponse.data.list.size() > 0) {
                                tv_task.setVisibility( View.GONE );
                                recyclerView_student_list.setVisibility( View.VISIBLE );
                                list.clear();
                                list.addAll( taskListResponse.data.list );
                                myAdapter.notifyDataSetChanged();
                            } else {
                                tv_task.setVisibility( View.VISIBLE );
                                recyclerView_student_list.setVisibility( View.GONE );
                            }

                        }
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                    //如果JSONException e，打印出来就 Log.e(TAG, e.toString() + "");
                }
            }

            @Override
            public void onError(Throwable e) {
                try {
                    if (loadMore){
                        currentPage --;
                    }
                    //这里写可能出现异常的语句
                    e.printStackTrace();
                    refreshLayout.finishRefresh( false );
                    NetUtil.onError( e, mContext );
                } catch (Exception e1) {
                }

            }

            @Override
            public void onComplete() {
                if (refreshLayout != null){
                    refreshLayout.finishRefresh();
                }
            }
        } );
    }


    private void showSchoolDialog(String taskSchoolId, String taskId, String schoolName) {
//        if (mClassDialog == null) {
//        mClassDialog = mClassDialog.newInstance();
//        mClassDialog.taskSchoolId = taskSchoolId;
//        mClassDialog.taskId = taskId;
//        mClassDialog.schoolName = schoolName;
//        mClassDialog.show(getChildFragmentManager(), "mClassDialog");
//        mClassDialog.setmListener(new ClassDialog.OnItemClickListener() {
//            @Override
//            public void onConfirm(String className) {
////                currentClass = className;
//            }
//        });
//        } else if (!mClassDialog.isAdded() && !mClassDialog.isShowing()) {
//            mClassDialog.show(getSupportFragmentManager(), "mClassDialog");
//        }
    }


    private void isTask(String taskId) {
        RestProxy.getInstance().isTask( taskId, new Observer<IsTaskDataResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(IsTaskDataResponse isTaskDataResponse) {
                if (isTaskDataResponse.data == 1) {

//                    bundle.getString("taskSchoolId");
//                    bundle.getString("taskId");
//                    bundle.getString("schoolName");
                    RestProxy.getInstance().isShowOther( taskId, new Observer<AxisResponse>() {


                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(AxisResponse axisResponse) {
                            LogUtil.e( "配置其他项" + axisResponse.data.other + "--" + axisResponse.data.Axis );
                            BaseApplication.isShowOther = axisResponse.data.other;
                            BaseApplication.isShowAxis = axisResponse.data.Axis;
                            Intent mIntent = new Intent();
                            mIntent.putExtra( "taskSchoolId", bundle.getString( "taskSchoolId" ) );
                            mIntent.putExtra( "taskId", bundle.getString( "taskId" ) );
                            mIntent.putExtra( "schoolName", bundle.getString( "schoolName" ) );
                            mContext.setResult( Activity.RESULT_OK, mIntent );
                            mContext.finish();
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            NetUtil.onError( e, mContext );
                        }

                        @Override
                        public void onComplete() {

                        }
                    } );

//                    showSchoolDialog(bundle.getString("taskSchoolId"),bundle.getString("taskId"),bundle.getString("schoolName"));
//                    startActivity(ClassActivity.class, bundle);
                } else if (isTaskDataResponse.data == 0) {
                    Toast.makeText( mContext, "任务未开始！", Toast.LENGTH_SHORT ).show();
                } else if (isTaskDataResponse.data == 2) {
                    Toast.makeText( mContext, "任务已结束！", Toast.LENGTH_SHORT ).show();
                }
            }

            @Override
            public void onError(Throwable e) {
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    private void updateTask(String taskId) {
        RestProxy.getInstance().updateTask( taskId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                getTaskList(false);
                Toast.makeText( mContext, "操作成功", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {
                mReviewDialog.dismiss();
            }
        } );
    }

    private void createReview(String taskId) {
        RestProxy.getInstance().createReview( taskId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                getTaskList(false);
                Toast.makeText( mContext, "操作成功", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, mContext );
            }

            @Override
            public void onComplete() {
                mReviewDialog.dismiss();
            }
        } );
    }


    /**
     * 年份弹窗
     *
     * @time 2020/5/27 9:17
     */
    private void showYearDialog() {
        if (mYearDialog == null) {
            mYearDialog = YearDialog.newInstance();
            mYearDialog.show( getChildFragmentManager(), "mYearDialog" );
            mYearDialog.setmListener( new YearDialog.OnItemClickListener() {
                @Override
                public void onConfirm(String planYear) {

                    if (!UtilString.isEmpty( planYear )) {
                        tvYear.setText( planYear );
                        mPlanYear = planYear;
                        getTaskList(false);
                    }

                    mYearDialog.dismiss();
                }
            } );
        } else if (!mYearDialog.isAdded() && !mYearDialog.isShowing()) {
            mYearDialog.show( getChildFragmentManager(), "mYearDialog" );
        }
    }


    private void showReviewDialog(String taskId, int type) {
//        if (mQualifiedDialog == null) {
        mReviewDialog = mReviewDialog.newInstance( type );
        mReviewDialog.show( getChildFragmentManager(), "mReviewDialog" );
        mReviewDialog.setmListener( new ReviewDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                if (type == 1) {
                    createReview( taskId );
                } else {
                    updateTask( taskId );
                }
            }

            @Override
            public void onCancel() {
                mReviewDialog.dismiss();
            }
        } );
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint( isVisibleToUser );
//        if (getUserVisibleHint()) {
//            LogUtil.d("__getTaskList-request-7","1");
//            getTaskList(false);
//        } else {
////界面不可见 相当于onpause
//        }
//    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView( inflater, container, savedInstanceState );
        unbinder = ButterKnife.bind( this, rootView );
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
